using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.IO;

namespace Logger
{
    public class LoggerWriter
    {
        private static LoggerWriter currentInstance = new LoggerWriter();

        private static string logFileKey    = "logFile";
        private static string logFileMode   = "logMode";
        private static string logFileAll    = "0";
        private static string logFileErrors = "1";

        public static LoggerWriter Current
        {
            get
            {
                return currentInstance;
            }
        }

        private void fileWrite(string log, string type, string message)
        {
            FileStream fs = null;

            if (File.Exists(log))
            {
                fs = File.Open(log, FileMode.Append);
            }
            else
            {
                fs = File.Create(log, 4096);
            }

            TextWriter tw = new StreamWriter(fs);

            tw.WriteLine(type +" | "+ DateTime.Now.ToString() + " | " + message);

            tw.Close();
        }

        public void Write(string message)
        {
            try
            {
                string logMode = logFileErrors;

                if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[logFileMode]))
                {
                    logMode = ConfigurationManager.AppSettings[logFileMode];
                }

                if (logMode == logFileErrors)
                {
                    return;
                }

                if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[logFileKey]))
                {
                    string log = ConfigurationManager.AppSettings[logFileKey];
                    log = log.Replace(".", DateTime.Now.ToString("yyyy-MM-dd") + ".");

                    fileWrite(log, "Message", message);
                }
            }
            catch
            {
            }
        }

        public void WriteError(string message)
        {
            try
            {
                if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[logFileKey]))
                {
                    string log = ConfigurationManager.AppSettings[logFileKey];
                    log = log.Replace(".", DateTime.Now.ToString("yyyy-MM-dd") + ".");

                    fileWrite(log, "Error  ", message);
                }
            }
            catch
            {
            }
        }
    }
}


